//评估记录
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  message,
  InputNumber,
  notification
} from 'antd';

import { connect } from 'dva';
import router from 'umi/router';
import axios from 'axios';
import Api from '../../services/apis';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formatTreeData } from '../../components/commonAips';
const confirm = Modal.confirm;
const FormItem = Form.Item;

@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class giveRole extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
      name: '',
      _name: '',
      _number: '',
      modalVisible: false,
      modifyVisible: false,
      newNumber: '',
      newName: '',
      newPassword: '',
      samePassword: '',
      newPhone: '',
      newDepartment: '',
      newArea: '',
      selectedId:[],
      tableData: [
        {
          area: 'sdfasdf',
          status: '123',
        },
        {
          area: 'sdfasdf',
          status: '123',
        },
      ],
    };
  }

  componentWillMount() {
    //获取表格数据
    this.sendData();
  }

  resetForm() {
    this.setState({
      number: '',
      name: '',
    });
  }

  sendData() {
    const that = this;

    axios
      .post(Api.umGetRolesByUser, {
        roleName: this.state.number,
        userId: this.props.location.query ? this.props.location.query.id : '',
      })
      .then(function(resp) {
        const {data} = resp;
        if (data) {
          let tmp = [];
          let selectedArr = [];
          for (let i = 0, len = data.length; i < len; i++) {
            tmp.push({
              key: i + 1,
              roleName: data[i].roleName,
              roleCode: data[i].roleCode,
              roleDesc: data[i].roleDesc,
              roleId: data[i].roleId,
            });
            if (data[i].userHaveRole) {
              selectedArr.push(i + 1);
            }
          }
          that.setState({
            tableData: tmp,
            totalSize: data.length,
            selectedArr: selectedArr,
            userId: that.props.location.query ? that.props.location.query.id : '',
          });
        }
      });
  }

  changeNumber = e => {
    this.setState({ number: e.target.value });
  };

  setModalVisible = () => {
    let that = this;
    if(this.state.selectedId.length!=0){
    
      let param = new URLSearchParams();
      param.append('funArray', this.state.selectedId.join(','));
      param.append('userId', this.state.userId);

      axios
        .post(Api.umGetRolesByUser, {
          funArray: this.state.selectedId.join(','),
          userId: this.state.userId,
        })
        .then(function(resp) {
          const {data} = resp;
          if (data && data.code == 1) {
            Modal.info({
              title: '信息',
              content: '授权成功',
              onOk() {},
            });
          } else {
            Modal.info({
              title: '信息',
              content: data.msg,
              onOk() {},
            });
          }
        });
      }else{
        notification.destroy();
        notification['warning']({message:'请选择列表项后进行操作！'})
      }
  };

  closeIframe = () => {
    let aaa = {
      pathname: '/fe/systemManagement/userEmpowerment',
      query: {
        number: this.state._number,
        name: this.state._name,
      },
    };
    router.push(aaa);
  };

  changeSelected = (selectedRowKeys, selectedRows) => {
    let selectedId = [];
    selectedRows &&
      selectedRows.map((item, index) => {
        selectedId.push(item.roleId);
      });

    this.setState({ selectedArr: selectedRowKeys, selectedId: selectedId });
  };

  render() {
    let that = this;
    //表头
    const columns = [
      {
        title: '角色',
        dataIndex: 'roleName',
        key: 'roleName',
      },
      {
        title: '描述',
        dataIndex: 'roleDesc',
        key: 'roleDesc',
      },
    ];

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        that.changeSelected(selectedRowKeys, selectedRows);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
    };
    const {
      currentUserLoading,
    } = this.props;

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
      <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>用户赋予角色</p>
              <p>USER ENDOW ROLE</p>
            </div>
          </div>
          <div className='clearfix'>
            <Button type='primary' className='pull-right' onClick={this.closeIframe}>返回</Button>
          </div>
        <div className='mrb15'>
          <Form layout="inline" align='center'>
              <FormItem>
                <span className="erlabel">角色名称：</span>
                <Input
                  value={this.state.number}
                  data-inp="zdbh"
                  onChange={this.changeNumber.bind(this)}
                  placeholder="请输入"
                />
              </FormItem>
              <Row gutter={24} style={{ textAlign: 'center'}}>
                <Button icon='search' type="primary" className="evfilterbtn" onClick={this.sendData.bind(this)}>
                  查询
                </Button>
                  &emsp;
                <Button
                  onClick={this.resetForm.bind(this)}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn" icon="reload"
                >
                  重置
                </Button>
                  &emsp;
                <Button
                  type="primary"
                  onClick={() => this.setModalVisible(true)}
                  icon="plus-circle"
                >
                  赋权
                </Button>
             </Row>
          </Form>
        </div>

        <Row className="choicedBox">
          <Table
            rowSelection={rowSelection}
            bordered={true}
            scroll={{x:true}}
            align={'center'}
            columns={columns}
            dataSource={this.state.tableData}
            pagination={{
              defaultPageSize: 5,
              total: that.state.totalSize,
              showTotal: total => `共 ${total} 项`
            }}
          />
        </Row>
    </div>
    </PageHeaderWrapper>
    );
  }
}

export default giveRole;
